//
//  uStationSelector.m
//  ElektroM
//
//  Created by Michael on 20.10.09.
//  Copyright 2009 Artgruppe inc. All rights reserved.
//

#import "uStationSelector.h"
#import "cellForUStation.h"
#import "dataBase.h"
#import "Constants.h"
#import "undergroundController.h"

@implementation uStationSelector
@synthesize table;
@synthesize navTitle;
@synthesize leftButton;
@synthesize searchBar;
@synthesize strSearch;
/*
@synthesize startStationId;
@synthesize endStationId;
*/

/*
 // The designated initializer.  Override if you create 
 // the controller programmatically and want to perform 
 // customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	//[self.navigationItem setPrompt: animated:YES];	
    self.navigationItem.prompt=NSLocalizedString(@"UndegroundStations", @"");
   	NSArray *segmentTextContent = [NSArray arrayWithObjects:NSLocalizedString(@"A_ZOrder", @""), 
								   NSLocalizedString(@"Lines", @""),nil];
	UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:segmentTextContent];
	segmentedControl.selectedSegmentIndex = 0;
	segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
	segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
	segmentedControl.frame = CGRectMake(0, 0, 300, kCustomButtonHeight);
	[segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];	
	
	// Load images for the lines symbols,
	// they should speed up the loading process:
	_aImagesForLines=(UIImage**)malloc(sizeof(UIImage)*kImagesForULinesCount);
	for(int i=0; i<kImagesForULinesCount; i++)
	    _aImagesForLines[i]=[UIImage imageNamed:
			 [NSString stringWithFormat:@"line%d.png", i+1]];

	self.navigationItem.titleView = segmentedControl;
	[segmentedControl release];
}

- (IBAction)segmentAction:(id)sender
{
	// The segmented control was clicked, handle it here 
	UISegmentedControl *segmentedControl = (UISegmentedControl *)sender;
	_nSegmentSelected=segmentedControl.selectedSegmentIndex;
	// lazy loading...
	if(_nSegmentSelected==1 && _diStationSortedByLineNames==nil){
		[_db initialization];
	    _diStationSortedByLineNames=[_db readUStationsAndOrderThemByLineNames];
	    _diStationIdsSortedByLineNames=[_db getUStationIdsSortedByLine];
	    _aiLineIdsUsedInSortingByLines=[_db getUStationsLineIdsUsedInStationsSortedByLine];
	    //_aiLineNamesUsedInSortingByLines=[_db getUStationLineNamesUsedInStationsSortedByLine];
	}	
	[table reloadData];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if(_nSegmentSelected==1)
	return nil;
    if(_bSearchInProgress)
	return nil;

    return _aiSortedLettersForUSt;
}

// read all info about lines and stations from DB
-(void) readAll
{
    [self readForTheLine:-1];
}

//read info with the line number lineNum
-(void) readForTheLine:(int)lineNum
{
		/*
	dataBase* db=[dataBase alloc];
	db.databaseName=kDBUnderground;
	
	// initialize our mighty db, please:

	[db initialization];
	_strUNames=[db readUStationsWithLineId:lineNum];
	_strULineNames=[db getULineNames];
	_nCount=[db getUStationsCount];
	_nULineNumbers=[db getULineNumbersSortByLines];

	[table reloadData];
	 */
}

-(IBAction) goBack
{
	[self.navigationController popViewControllerAnimated:YES];	
}

-(void)setStationsInfo:(NSArray*)aLines
		 withCount:(int)count 
		 andController:(undergroundController*)controller 
		 andDb:(dataBase*)db
{
	//_strUNames=st;
	myMaster=controller;
	_db=db;	
	_nCount=count;
	_aiULineNames = aLines;
	//_strULineNames=lines;
	//_nULineNumbers=numbers;
}

#pragma mark -
#pragma mark Search Methods
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{    	
    if([searchText length]==0)return;	
    _bSearchInProgress=true;

    self.strSearch=searchText;
	//[self.strSearch retain];
    [self performSearch: strSearch];
}

-(void) performSearch: (NSString*) searchText
{
    if(_anIndexesStFound==nil){
		_anIndexesStFound=(NSUInteger*)malloc(sizeof(NSUInteger)*[_aiAllStationNames count]);
		//printf("Alloc indexes!\n");
	}
    //_anIndexesStFound=(NSUInteger*)malloc(sizeof(NSUInteger)*_nCount);

    _nSearchedStations=0;	
    for(int i=0; i<[_aiAllStationNames count]; i++){
	//NSRange range=[_strUNames[i] rangeOfString:searchText options:NSCaseInsensitiveSearch];
	NSRange range=[[_aiAllStationNames objectAtIndex:i] 
					   rangeOfString:searchText options:NSCaseInsensitiveSearch];	
	if(range.location!=NSNotFound){
	    _anIndexesStFound[_nSearchedStations++]=i;
	}
    }
	_bSearchWasPerformed=true;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    _bSearchInProgress=false;

    [table reloadData];
}

#pragma mark -
#pragma mark Table Sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
   	if(!_bSearchInProgress){
	if(_nSegmentSelected==0){
		return [_aiSortedLettersForUSt count];
	}
	else{
	    return [[_diStationSortedByLineNames  allKeys] count];
	}
    }
    else
	return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{	
    if(!_bSearchInProgress){	
	if(_nSegmentSelected==0){		
	    return [[_diAllStationsWithIndexes objectForKey:[_aiSortedLettersForUSt objectAtIndex:section]] count];	
	}
	else
	{
		NSArray* keys=[_diStationSortedByLineNames allKeys];
		return [[_diStationSortedByLineNames objectForKey:[keys objectAtIndex:section]] count];		
	}
    }
    else
		return _nSearchedStations;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	if(table != tableView)
		table = tableView;
	
	if(!_bSearchInProgress){
	    if(_nSegmentSelected==0)
		return [_aiSortedLettersForUSt objectAtIndex:section];
	    else{
			NSArray* keys=[_diStationSortedByLineNames allKeys];
			return [keys objectAtIndex:section];
		}
	}
	return @"";
}
#pragma mark -
#pragma mark Rows Naming
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{	
	static NSString *kCellIdentifier = @"cellID";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
	if (!cell)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kCellIdentifier] autorelease];
        
		cell.accessoryType = UITableViewCellAccessoryNone;
        
		cell.textLabel.backgroundColor = [UIColor clearColor];
		cell.textLabel.opaque = NO;
		cell.textLabel.textColor = [UIColor blackColor];
		cell.textLabel.highlightedTextColor = [UIColor whiteColor];
		cell.textLabel.font = [UIFont boldSystemFontOfSize:18];

		cell.detailTextLabel.backgroundColor = [UIColor clearColor];
		cell.detailTextLabel.opaque = NO;
		cell.detailTextLabel.textColor = [UIColor grayColor];
		cell.detailTextLabel.highlightedTextColor = [UIColor whiteColor];
		cell.detailTextLabel.font = [UIFont systemFontOfSize:10];
	}   
		
    if(!_bSearchInProgress){
	if(_nSegmentSelected==0){
	    NSNumber* str=[[_diSortedLineNumbers
		objectForKey:[_aiSortedLettersForUSt objectAtIndex:indexPath.section]] 
	       objectAtIndex:indexPath.row];

	    int index=[str intValue];	  
	    cell.imageView.image=_aImagesForLines[index-1];

	    cell.textLabel.text = [[_diAllStationsWithIndexes
		objectForKey:[_aiSortedLettersForUSt objectAtIndex:indexPath.section]] 
	       objectAtIndex:indexPath.row];

	    NSNumber* strId=[[_diSortedStationIds
		objectForKey:[_aiSortedLettersForUSt objectAtIndex:indexPath.section]] 
	       objectAtIndex:indexPath.row];
	    cell.detailTextLabel.text=[_aiULineNames objectAtIndex: [strId intValue]];
	    //_strULineNames[[strId integerValue]];
	}
	else{		
	    //    [_aiLineNamesUsedInSortingByLines objectAtIndex:indexPath.section];
	    NSString* key =
		[[_diStationSortedByLineNames allKeys] objectAtIndex:indexPath.section];
	    cell.textLabel.text = [[_diStationSortedByLineNames objectForKey:key] objectAtIndex:indexPath.row];
	    //printf("Id of image: %d\n", [[_aiLineIdsUsedInSortingByLines objectAtIndex: indexPath.section] integerValue]);
	    cell.imageView.image= _aImagesForLines[
		[[_aiLineIdsUsedInSortingByLines objectAtIndex: indexPath.section] intValue]-1
		];
	    cell.detailTextLabel.text=@"";
	}
    }
    else    
    {		
		//printf("Index: %d %d\n", indexPath.row, [_aiULineNames count]);
		//printf("Seach was performed: %d\n", _bSearchWasPerformed?1:0);
		if(!_bSearchWasPerformed){
		    //printf("Perform search!\n");
			//[self loadAllNeededElements:_db];
		    [self performSearch: self.strSearch];		    
		}
		/*	
	printf("Index: %d %d\n", indexPath.row, [_aiAllStationLineIds count]);		
	if([_aiStationsInLineCount count]<=10)
	{

	}

	   if(indexPath.row >= _nSearchedStations)
	   {
	   return cell;
	   }

	   for(int i=0; i<_nSearchedStations; i++)		
	   printf("%d. Found nums: %d\n", i, _anIndexesStFound[i]);
	   */
	//printf("Image load...\n");
	cell.imageView.image=
	    _aImagesForLines[
	    [[_aiAllStationLineIds objectAtIndex:_anIndexesStFound[indexPath.row]] intValue]-1
	    ];

	//printf("Station name load...\n");
	cell.textLabel.text=[_aiAllStationNames objectAtIndex:_anIndexesStFound[indexPath.row]];		
	//printf("Line name load...\n");
	cell.detailTextLabel.text=[_aiULineNames objectAtIndex: [[_aiAllStationLineIds objectAtIndex: 
	    _anIndexesStFound[indexPath.row]] intValue]];
    }

    return cell;
}

#pragma mark -
#pragma mark Table Delegate Methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {	    
	if(!_bSearchInProgress){
	// get indexes from our map:
	if(_nSegmentSelected==0){
	    NSNumber* str=[[_diSortedStationIds
		objectForKey:[_aiSortedLettersForUSt objectAtIndex:indexPath.section]] 
	       objectAtIndex:indexPath.row];

	    [myMaster setSelection:[str intValue]];
	}
	else
	{
	    NSString* key=
		[[_diStationSortedByLineNames allKeys] objectAtIndex:indexPath.section];
	    int idRet=[[[_diStationIdsSortedByLineNames objectForKey:key] objectAtIndex:indexPath.row] intValue];
	    _bSearchWasPerformed=false;
	    
	    // all indexes in that db are less then real ones by 1:
	    [myMaster setSelection: idRet-1];	    
	}
    }
    else{
		
	[myMaster setSelection:[[_aiAllStationIds objectAtIndex:
	 _anIndexesStFound[indexPath.row]] intValue]];
		//printf("text to search: %s\n", [strSearch UTF8String]);
    }
	//[self.navigationController.navigationBar setHidden:YES];	
   [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark Releasing elements and stuff
-(void) releaseUnneededElements
{
    //printf("Unneded Elements were freed!\n");    
   
	free(_anIndexesStFound);
   _anIndexesStFound=nil;
	       
    if(_diAllStationsWithIndexes!=nil)
	[_diAllStationsWithIndexes release];
    if(_diSortedStationIds!=nil)
	[_diSortedStationIds release];
    if(_diSortedLineNumbers!=nil)
	[_diSortedLineNumbers release];
   if(_aiSortedLettersForUSt!=nil)
	[_aiSortedLettersForUSt release];
    if(_aiAllStationNames!=nil)
	[_aiAllStationNames release];
    if(_aiAllStationIds!=nil)
	[_aiAllStationIds release];
    if(_aiAllStationLineIds!=nil)
    	[_aiAllStationLineIds release];
    if(_diStationIdsSortedByLineNames!=nil)
	[_diStationIdsSortedByLineNames release];
    if(_diStationSortedByLineNames!=nil){
	[_db cleanAllResourcesOfUStationNamesWithAlpOrd];
	[_diStationSortedByLineNames release];
    }
    if(_aiLineIdsUsedInSortingByLines!=nil)
	[_aiLineIdsUsedInSortingByLines release];
    /*
    if(_aiLineNamesUsedInSortingByLines!=nil)
	[_aiLineNamesUsedInSortingByLines release];
	*/
    /*
	 if(_aiStationsInLineCount!=nil)
	 [_aiStationsInLineCount release];

	if(_aiAllStationIdsBeforeSort!=nil)
	[_aiAllStationIdsBeforeSort release];
	 */
    _aiAllStationLineIds=nil;
    _aiAllStationIds=nil;
    _aiAllStationNames=nil;
    _diSortedLineNumbers=nil;
    _diSortedStationIds=nil;
    _diAllStationsWithIndexes=nil;
    _aiSortedLettersForUSt=nil;
    _diStationIdsSortedByLineNames=nil;
    _diStationSortedByLineNames=nil;
    _aiLineIdsUsedInSortingByLines=nil;
    //_aiLineNamesUsedInSortingByLines=nil;
    /*
	_aiStationsInLineCount=nil;
    _aiAllStationIdsBeforeSort=nil;
	 */
    [_db releaseUStationAsNSArrayResources];
}

-(void) loadAllNeededElements:(dataBase*)db
{
	// all needed elements were loaded
	//printf("all needed elements were loaded\n");
	_db=db;
	[db initialization];	
	
	_diAllStationsWithIndexes=[db readUStationsAsNSArrayAndFormThemAlpabetically];
	    //[db readUStationsAndFormThemAlpabetically];
	_aiSortedLettersForUSt=[[_diAllStationsWithIndexes allKeys] 
							sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
	[_diAllStationsWithIndexes retain];
	[_aiSortedLettersForUSt retain];
	_aiAllStationNames=[db getAllStationsNameInAppleFormat];
	[_aiAllStationNames retain];
	_aiAllStationIds=[db getAllStationsIdsInAppleFormat];
	/*
	printf("------------\n");
	for(id value in _aiAllStationIds)
	    printf("Station id: %d\n", [value intValue]);
	[_aiAllStationIds retain];
	*/

	_aiAllStationLineIds=[db getAllStationsLineIdsInAppleFormat];
	[_aiAllStationLineIds retain];
	
	// get info about stations sorted by line names:
	// lazy loading...
	if(_nSegmentSelected==1){
	    _diStationSortedByLineNames=[db readUStationsAndOrderThemByLineNames];
	    _diStationIdsSortedByLineNames=[db getUStationIdsSortedByLine];
	    _aiLineIdsUsedInSortingByLines=[db getUStationsLineIdsUsedInStationsSortedByLine];

	 //   _aiLineNamesUsedInSortingByLines=[db getUStationLineNamesUsedInStationsSortedByLine];
	}
	
	_diSortedLineNumbers=[db getULineNumbersSortedAlp];
	/*
	for(id key in [_diSortedLineNumbers allKeys])
	{
		for(id value in [_diSortedLineNumbers objectForKey: key])
		{
			printf("Key %s; Value: %s\n", [key UTF8String], [value UTF8String]);
		}			
	}
	 */	
	_diSortedStationIds = [db getUStationNumbersSortedAlp];
	// set search flag to zero, we do not want confuse the user:
	_bSearchInProgress=false;	

	[table reloadData];
}

- (void)viewWillAppear:(BOOL)animated{
	//[self.navigationController setToolbarHidden:NO];
	//table = (UITableView*)[self.view viewWithTag:111];	
	/*
	 printf("Search string: %s %d\n", [strSearch UTF8String], _bSearchWasPerformed?1:0);
	self.navigationController.toolbar.hidden=NO;// setToolbarHidden:YES animated:NO];
	self.navigationController.toolbarHidden=NO;
	*/	
    [self loadAllNeededElements:_db];	
	if(!_bSearchWasPerformed && strSearch!=nil)
	{	
		//printf("Perform search! %s\n", [strSearch UTF8String]);
		//[self performSearch: strSearch];	
		//[(UITableView*)[self.view viewWithTag:111] reloadData];		
		[self.searchBar setText: strSearch];
		//[table reloadData];
		
	}
	
	if(_bSearchInProgress)
	{		
	    // we need to start search once again; for updating our array:
	    //printf("Search text is: %s\n", [strSearch UTF8String]);
	    /*
	       for(int i=0; i<_nSearchedStations; i++)
	       printf("%d. Searched num: %d\n", i, _anIndexesStFound[i]);
	       */
	    [self performSearch: self.strSearch];	
		[table reloadData];		
	}	
	[self.navigationController setNavigationBarHidden:NO animated:NO];
	[self.navigationController.navigationBar setHidden:NO];
	//if(_diAllStationsWithIndexes==nil)
}

- (void)viewWillDisappear:(BOOL)animated{
	//[self.navigationController setToolbarHidden:YES];
    /*
	self.navigationController.toolbar.hidden=YES;// setToolbarHidden:YES animated:NO];
	self.navigationController.toolbarHidden=YES;
	*/
	self.navigationController.navigationBarHidden=YES;
	[self.navigationController setNavigationBarHidden:YES animated:NO];
	//[self searchBarCancelButtonClicked:searchBar];
	_bSearchWasPerformed=false;
	
    [self releaseUnneededElements];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
    /*
	 // If I uncomment the strings here, I would get all the time I used search
	 // the error of using not allocated space of memory
	if(_anIndexesStFound!=NULL)
	free(_anIndexesStFound);
	 */
    if(_aiAllStationNames!=nil)
		[self releaseUnneededElements];
	self.table=nil;
	self.searchBar=nil;
	self.leftButton=nil;
	self.navTitle=nil;
	
	for(int i=0; i<kImagesForULinesCount; i++){
	    [_aImagesForLines[i] release];
		_aImagesForLines[i]=nil;
	}
	
	//free(_aImagesForLines);
	
	if(_db!=nil)
	{
		_db.namePrefix=nil;
		_db.databaseName=nil;
		[_db cleanAllResourcesOfUStationNamesWithAlpOrd];
		[_db release];
		_db=nil;
	}
	self.strSearch=nil;
	//printf("View unloaded!\n");
}


- (void)dealloc {
    [super dealloc];
}
@end
